<template>
  <el-button type="primary" @click="dialogVisible=true">添加</el-button>
  <el-divider direction="vertical"></el-divider>
  <el-button :icon="Refresh" :loading="loading" @click="refreshTable">
    <span>刷新</span>
  </el-button>
  <!--添加标签弹出框-->
  <el-dialog
      v-model="dialogVisible"
      :title="isAdd?'添加':'修改'"
      width="30%"
      :before-close="handleClose">
    <el-form ref="formRef"
             :model="albumFrom"
             :rules="rules"
             label-width="80px">
      <el-form-item label="相册名称" prop="albumName">
        <el-input v-model="albumFrom.albumName" type="text" maxlength="20"
                  show-word-limit/>
      </el-form-item>
      <el-form-item label="相册描述" prop="albumDescription">
        <el-input v-model="albumFrom.albumDescription" type="textarea"
                  :autosize="{ minRows: 2, maxRows: 5 }"
                  maxlength="50" show-word-limit/>
      </el-form-item>
      <!--  相册封面 -->
      <el-form-item label="相册封面" prop="albumCover">
        <el-upload
            class="avatar-uploader"
            name="albumCover"
            :auto-upload="true"
            action="/api/album/uploadImg"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <el-image fit="cover" v-if="getUploadImgUrl" :src="getUploadImgUrl" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <!--  分类是否启用 -->
      <el-form-item label="是否展示" prop="isShow">
        不展示
        <el-switch v-model="albumFrom.isShow" style="margin: 0 10px;"/>
        展示
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="saveAlbum">
          保存
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
  <el-divider></el-divider>
  <!-- 相册展示区-->
  <el-space wrap size="large">
    <el-card v-for="item in tableData"
             :key="item.albumId"
             :body-style="{padding: '0px'}"
             style="width: 250px;">
      <template #header>
        <div class="card-header">
          <el-link @click="toPictureManage(item.albumId)">{{ item.albumName }}</el-link>
        </div>
      </template>
      <el-tooltip
          effect="dark"
          :content="item.albumDescription"
          placement="bottom">
        <el-image :src="item.albumCover"
                  @click="toPictureManage(item.albumId)"
                  fit="cover"
                  style="width: 250px;height: 180px;border: 1px solid #eae5e5"></el-image>
      </el-tooltip>

      <el-popconfirm title="删除相册将删除此相册内的所有照片，确认删除吗？" @confirm="deleteAlbum(item.albumId)">
        <template #reference>
          <el-button text style="float: right;color: red">
            <el-icon>
              <Delete/>
            </el-icon>
          </el-button>
        </template>
      </el-popconfirm>

      <el-tooltip
          effect="dark"
          content="修改相册信息"
          placement="bottom">
        <el-button text style="float: right" @click="editAlbum(item)">
          <el-icon>
            <Edit/>
          </el-icon>
        </el-button>
      </el-tooltip>
      <!--<span style="margin-left: 10px">{{item.albumDescription}}</span>-->
      <el-tooltip
          effect="dark"
          :content="item.isShow ? '前端展示':'前端隐藏'"
          placement="bottom">
        <el-switch :loading="loading" v-model="item.isShow" @change="updateAlbum(item)"
                   style="float: right;margin-right: 10px"/>
      </el-tooltip>
      <span style="margin-left: 10px">{{ item.pictureCount }} P</span>
    </el-card>
  </el-space>

  <el-divider></el-divider>
  <!--分页-->
  <div style="display: flex;">
    <el-pagination
        v-model:current-page="current"
        v-model:page-size="size"
        :page-sizes="[15, 30, 45, 60]"
        :small="true"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin: auto;"
    />
  </div>

</template>

<script>
import {Refresh, Search} from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";

export default {
  name: "Album",
  computed: {
    getUploadImgUrl() {
      if (this.uploadImgUrl) {
        return this.uploadImgUrl
      } else {
        return ""
      }
    },
  },
  data() {
    return {
      Refresh, Search,
      // 上传图片的url
      uploadImgUrl: "",
      loading: false,
      searchText: "",
      dialogVisible: false,
      // false 表示修改标签
      isAdd: true,
      albumFrom: {
        albumId: null,
        albumName: "",
        albumDescription: "",
        albumCover: 1,
        isShow: true,
      },
      rules: {
        albumName: [
          {required: true, message: '请输入相册名称', trigger: 'blur'},
          {min: 1, max: 20, message: '相册名称长度应该在1-20', trigger: 'blur'},
        ],
        albumDescription: [
          {max: 50, message: '相册描述长度应该小于50', trigger: 'blur'},
        ],
      },
      tableData: [],
      total: 0,
      current: 1,
      size: 8,
    }
  },
  created() {
    this.getAll()
  },
  methods: {
    async getAll() {
      let {data: result} = await this.$http.get("/api/album/getAlbums", {
        params: {
          pageSize: this.size,
          pageNum: this.current,
        }
      })
      this.tableData = result.dataMap.page.records
      this.current = result.dataMap.page.current
      this.total = result.dataMap.page.total
      this.size = result.dataMap.page.size
    },
    refreshTable() {
      this.loading = true
      this.getAll()
      this.loading = false
    },
    handleClose() {
      this.$refs.formRef.resetFields()
      this.dialogVisible = false
      // 将添加表单初始化
      this.$data.albumFrom = this.$options.data().albumFrom
      this.uploadImgUrl = ""
      this.isAdd = true
    },
    editAlbum(item) {
      // es6 新特性，深拷贝
      this.albumFrom = {...item}
      this.uploadImgUrl = item.albumCover
      this.isAdd = false
      this.dialogVisible = true
    },
    async updateAlbum(album) {
      let item = {...album}
      let {data: result} = await this.$http.post("/api/album/save", item)
      if (result.code === 400) {
        ElMessage.error({
          showClose: true, message: result.msg
        })
      } else {
        ElMessage.success({
          showClose: true, message: result.msg
        })
        this.refreshTable()
      }
    },
    saveAlbum() {
      this.$refs.formRef.validate(async (validate) => {
        if (validate) {
          let {data: result} = await this.$http.post("/api/album/save", this.albumFrom)
          if (result.code === 400) {
            ElMessage.error({
              showClose: true, message: result.msg
            })
          } else {
            ElMessage.success({
              showClose: true, message: result.msg
            })
            this.handleClose()
            this.refreshTable()
          }
        } else {
          ElMessage.error({
            showClose: true, message: "表单填写有误！"
          })
        }
      })
    },
    async deleteAlbum(albumId) {
      this.loading = true
      let {data: result} = await this.$http.get("/api/album/deleteAlbum", {
        params: {
          id: albumId,
        }
      })
      if (result.code !== 200) {
        ElMessage.error({
          showClose: true, message: result.msg
        })
      } else {
        ElMessage.success({
          showClose: true, message: result.msg
        })
      }
      this.refreshTable()
    },
    toPictureManage(albumId) {
      this.$router.push({name: "picture", params: {albumId: albumId}})
    },
    // 上传前检查文件格式和大小
    beforeAvatarUpload(rawFile) {
      // console.log(rawFile.type)
      // console.log(typeof rawFile.type)
      // console.log(rawFile.type !== 'image/jpeg')
      let allowTypes = ['image/jpeg', "image/jpg", 'image/png', 'image/webp', 'image/icon'];
      if (!allowTypes.includes(rawFile.type)) {
        ElMessage.error('文件格式不正确!')
        return false
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件大小不能大于 2MB!')
        return false
      }
      return true
    },
    // 上传成功修改预览
    handleAvatarSuccess(response) {
      console.log(response)
      let {code, dataMap} = response
      this.uploadImgUrl = dataMap.imgPath
      this.albumFrom.albumCover = dataMap.imgPath
    },
    // 分页大小改变
    handleSizeChange() {
      this.refreshTable()
    },
    // 分页页数改变
    handleCurrentChange() {
      this.refreshTable()
    },
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
  /*margin-left: 30px;*/
  border-radius: 20px;
}

.avatar-uploader {
  border: 1px solid #8c939d;
  border-radius: 20px;
  margin-left: 30px;
  height: 150px;
  width: 150px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  display: flex;
}


.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 140px;
  height: 60px;
  align-items: center;
  text-align: center;
}
</style>